<template>
  <el-card>
    <div style="max-height: calc(100vh - 150px); overflow-y: auto;">
    <el-form label-width="200px" ref="formRef">
      <!-- 公告内容 -->
      <el-form-item label="公告内容">
        <el-row style="width: 100%" :gutter="10">
          <el-col :span="20">
            <el-input
                v-model="settings.notice"
                type="textarea"
                :rows="4"
                placeholder="请输入公告内容"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="saveSetting('notice', settings.notice)">保存</el-button>
          </el-col>
        </el-row>
      </el-form-item>


      <el-form-item label="顶部视频">
        <el-upload
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            :file-list="fileListTop"
            :on-change="(file, fileList) => handleVideoChange(file, fileList)"
            :on-remove="(file, fileList) => handleVideoRemove(file, fileList)"
            accept="video/mp4"
            list-type="text"
        >
          <el-button type="primary">上传视频</el-button>
        </el-upload>

        <div style="font-size: 12px; color: #999;">最多上传 1 个视频, 仅支持 MP4 格式, 最大 8MB</div>
      </el-form-item>

      <!-- 下轮播图 -->
      <el-form-item label="下公告">
        <el-upload
            class="upload-demo"
            :auto-upload="false"
            :limit="6"
            list-type="picture-card"
            :file-list="fileListBottom"
            :on-change="(file, fileList) => handleImageChange(file, fileList, 'bottom')"
            :on-remove="(file, fileList) => handleImageRemove(file, fileList, 'bottom')"
            accept="image/jpeg,image/png"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <div v-for="(item, index) in settings.swipeBottom" :key="item.uid" style="margin: 10px 0;">
          <div style="margin-bottom: 6px; font-weight: bold;">图 {{ index + 1 }} 对应文章</div>
          <quill-editor
              v-model:content="item.content"
              :options="editorOptions"
              contentType="html"
              toolbar="full"
              style="border: 1px solid #ccc; min-width: 100%"

          />
          <el-button
              type="primary"
              size="small"
              style="margin-top: 6px;"
              @click="saveSwipeBottomItem(index)"
          >保存</el-button>
        </div>
      </el-form-item>

      <!-- 默认积分 -->
      <el-form-item label="默认积分">
        <el-row :gutter="10">
          <el-col :span="20">
            <el-input-number v-model="settings.defaultPoint" :min="0" style="width: 100%" />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="saveSetting('defaultPoint', settings.defaultPoint)">保存</el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <!-- 可提前预约天数 -->
      <el-form-item label="可提前预约天数">
        <el-row :gutter="10">
          <el-col :span="20">
            <el-input-number v-model="settings.advanceReservationDay" :min="0" style="width: 100%" />
          </el-col>
          <el-col :span="4">
            <el-button
                type="primary"
                @click="saveSetting('advanceReservationDay', settings.advanceReservationDay)"
            >保存</el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="预约前后可操作时间(分)">
        <el-row :gutter="10">
          <el-col :span="20">
            <el-input-number v-model="settings.advanceReservationDay" :min="0" style="width: 100%" />
          </el-col>
          <el-col :span="4">
            <el-button
                type="primary"
                @click="saveSetting('advanceReservationDay', settings.advanceReservationDay)"
            >保存</el-button>
          </el-col>
        </el-row>
      </el-form-item>

    </el-form>

    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import { QuillEditor } from '@vueup/vue-quill'


import '@vueup/vue-quill/dist/vue-quill.snow.css';

import request from '@/apps/admin/utils/request'

const fileListTop = ref([])
const fileListBottom = ref([])

const settings = ref({
  defaultPoint: null,
  notice: '',
  swipeTop: [],
  swipeBottom: [],
  advanceReservationDay: null
})

// Quill 编辑器配置
const editorOptions = {
  placeholder: '请输入内容',
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline'],
      [{ list: 'ordered' }, { list: 'bullet' }],
      ['link', 'image'],
      ['clean']
    ]
  }
}

// 图片上传
const handleImageChange = async (file, fileListRaw, type) => {
  const formData = new FormData()
  formData.append('file', file.raw)

  try {
    const res = await request.post('/v1/admin/uploadImg', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    const url = res.data.url
    const uid = file.uid

    if (type === 'top') {
      fileListTop.value = fileListRaw
      settings.value.swipeTop.push(url)
      saveSetting('swipeTop', settings.value.swipeTop)
    } else {
      fileListBottom.value = fileListRaw
      const item = { img: url, content: '', uid }
      settings.value.swipeBottom.push(item)
      saveSetting('swipeBottom', settings.value.swipeBottom)
    }
  } catch (e) {
    ElMessage.error('上传失败')
  }
}

const saveSwipeBottomItem = (index) => {
  const key = 'swipeBottom'
  saveSetting(key, settings.value.swipeBottom)
}

const handleImageRemove = (file, fileListRaw, type) => {
  if (type === 'top') {
    const newUrls = fileListRaw.map(item => item.url.replace('/api/src/img/', ''))
    fileListTop.value = fileListRaw
    settings.value.swipeTop = newUrls
    saveSetting('swipeTop', newUrls)
  } else {
    const removedUid = file.uid
    fileListBottom.value = fileListRaw
    settings.value.swipeBottom = settings.value.swipeBottom.filter(item => item.uid !== removedUid)
    saveSetting('swipeBottom', settings.value.swipeBottom)
  }
}

// 保存配置
const saveSetting = (key, value) => {
  const payload = {
    key,
    value: typeof value === 'object' ? JSON.stringify(value) : value
  }

  request.post('/v1/admin/updateSystemConfig', payload, {
    headers: { 'Content-Type': 'application/json' }
  })
      .then(() => ElMessage.success(`已保存：${key}`))
      .catch(err => {
        ElMessage.error('保存失败: ' + err.response.data.msg)
        console.error(err)
      })
}

// 初始化数据
request.get('/v1/admin/getSystemConfig').then(res => {
  const data = res.data || {}

  fileListTop.value = (data.swipeTop || []).map((url, index) => ({
    name: `top_${index}.jpg`,
    url: '/api/src/img/' + url,
    status: 'finished',
    uid: Date.now() + index
  }))

  const swipeBottomRaw = Array.isArray(data.swipeBottom) ? data.swipeBottom : []

  fileListBottom.value = swipeBottomRaw.map((item, index) => {
    const uid = Date.now() + 100 + index
    item.uid = uid
    return {
      name: `bottom_${index}.jpg`,
      url: '/api/src/img/' + item.img,
      status: 'finished',
      uid
    }
  })

  settings.value = {
    ...settings.value,
    ...data,
    swipeBottom: swipeBottomRaw
  }
})


const videoUrl = ref('')

// 处理视频上传
const handleVideoChange = async (file, fileListRaw) => {
  const formData = new FormData()
  formData.append('file', file.raw)

  try {
    const res = await request.post('/v1/admin/uploadVideo', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    const url = res.data.url
    fileListTop.value = fileListRaw
    videoUrl.value = '/api/src/img/' + url
    settings.value.swipeTop = [url] // 存储的是原始路径
    saveSetting('swipeTop', settings.value.swipeTop)
  } catch (e) {
    ElMessage.error('上传失败')
  }
}

const handleVideoRemove = (file, fileListRaw) => {
  fileListTop.value = []
  videoUrl.value = ''
  settings.value.swipeTop = []
  saveSetting('swipeTop', [])
}

</script>

<style scoped>
.upload-demo {
  width: 100%;
}
</style>
